package cn.lizemin.match;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class MyRegex {

    @Test
    public void test1(){
        String s = "the quick brown fox jumps _over the lazy dog.";
        // \w表示（A-Za-z0-9_）中的任意一个字符，不能是空格。这里的意思是要匹配3个字符，中间的字符必须是o.
        Pattern p = Pattern.compile("\\wo\\w");
        Matcher m = p.matcher(s);
        int i = 1;
        while (m.find()) {
            System.out.println("第" + i + "开始：" + m.start());
            System.out.println("第" + i + "结束：" + m.end());

            String sub = s.substring(m.start(), m.end());
            System.out.println(sub);
            i++;

        }

    }
    
    @Test
    public void test3(){
        String s = "The     quick\t\t brown   fox  jumps   over the  lazy dog.";

        //至少一个空格，替换成一个空格
        String r = s.replaceAll("\\s+", " ");
        System.out.println(r); // "The quick brown fox jumps over the lazy dog."
    
    }

    @Test
    public void test4(){
        //利用正则表达式匹配后的替换
        String s = "the quick brown fox jumps _over the lazy dog.";
        // \w表示（A-Za-z0-9_）中的任意一个字符，不能是空格。这里的意思是要匹配3个字符，中间的字符必须是o.
        Pattern p = Pattern.compile("\\wo\\w");
        Matcher m = p.matcher(s);
        StringBuffer sb = new StringBuffer();
        while (m.find()){
            m.appendReplacement(sb,"dog");
        }
        m.appendTail(sb);
        //the quick bdogn dog jumps doger the lazy dog.
        System.out.println(sb.toString());
    }

    @Test
    public void test5(){
        Pattern p = Pattern.compile("cat");
        Matcher m = p.matcher("one cat two cats in the yard");
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "dog");
        }
        m.appendTail(sb);
        System.out.println(sb.toString());

    }

    @Test
    public void test2(){
        String str = "lizemin in foshan";
        String substring = str.substring(2, 5);//[2,5)
        int index = str.indexOf('l');
        System.out.println(substring);
        System.out.println(index);

        String str2 = "li ze";//空格也是字符
        System.out.println(str2.length());

    }
    
    

}
